#include "userupdate.h"
#include "ui_userupdate.h"
#include <QMessageBox>
#include <QJsonObject>
#include "usermanager.h"

UserUpdateWindow::UserUpdateWindow(QWidget *parent)
    : QWidget(parent)
    , userupdatewindowUi(new Ui::UserUpdateWindow)
    , networkManager(new NetworkManager(this))
{
    userupdatewindowUi->setupUi(this);
    userupdatewindowUi->newRoleComboBox->addItems({"user", "admin"});

    if (UserManager::instance().getRole() == UserManager::User) {
        userupdatewindowUi->usernameLineEdit->setText(UserManager::instance().getUsername());
        userupdatewindowUi->usernameLineEdit->setReadOnly(true);
        userupdatewindowUi->newRoleComboBox->setEnabled(false);
    }

    connect(networkManager, &NetworkManager::updateUserResponseReceived, this, &UserUpdateWindow::handleUpdateUserResponse);
}

UserUpdateWindow::~UserUpdateWindow()
{
    delete userupdatewindowUi;
}

void UserUpdateWindow::on_updateButton_clicked()
{
    QString username = userupdatewindowUi->usernameLineEdit->text();
    QString newUsername = userupdatewindowUi->newUsernameLineEdit->text();
    QString newPassword = userupdatewindowUi->newPasswordLineEdit->text();
    QString newRole = userupdatewindowUi->newRoleComboBox->currentText();


    if (username.isEmpty() || (newUsername.isEmpty() && newPassword.isEmpty())) {
        QMessageBox::warning(this, "输入错误", "请填写所有必填字段。");
        return;
    }

    QJsonObject userInfo;
    userInfo["username"] = username;
    userInfo["new_username"] = newUsername;
    userInfo["new_password"] = newPassword;
    userInfo["new_role"] = newRole;

    networkManager->updateUser(userInfo);
}

void UserUpdateWindow::handleUpdateUserResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();
    if (code == 200) {
        QMessageBox::information(this, "用户信息更新成功！", desc);
    } else {
        QMessageBox::warning(this, "用户信息更新失败", desc);
    }
}

void UserUpdateWindow::on_resetButton_clicked()
{
    userupdatewindowUi->usernameLineEdit->clear();
    userupdatewindowUi->newUsernameLineEdit->clear();
    userupdatewindowUi->newPasswordLineEdit->clear();
    userupdatewindowUi->newRoleComboBox->setCurrentIndex(0);
}
